package com.pan.tools;


import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.Collections;
import java.util.stream.Collectors;

public class CookieTools {
    public static Cookie getCookie(HttpServletRequest request,String name, String value){
        Cookie cookie = new Cookie(name,value);
        String domain = getDomainName(request);
        cookie.setDomain(domain);
        cookie.setMaxAge(604800000);
        cookie.setPath("/");
        return cookie;
    }
    private static final void doSetCookie(HttpServletRequest request, HttpServletResponse response,
                                          String cookieName, String cookieValue, int cookieMaxage, boolean isEncode) {
        try {
            cookieValue = URLEncoder.encode(cookieValue, "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        Cookie cookie = new Cookie(cookieName, cookieValue);
        if (cookieMaxage > 0)
            cookie.setMaxAge(cookieMaxage);
        if (null != request) {
            String domainName = getDomainName(request);
            if (!"localhost".equals(domainName)) {
                cookie.setDomain(domainName);
            }
        }
        cookie.setPath("/");
        response.addCookie(cookie);
    }
    private static final String getDomainName(HttpServletRequest request) {
        String domainName;
        String serverName = request.getRequestURL().toString();
        if (serverName == null || serverName.equals("")) {
            domainName = "";
        }
        else {
            serverName = serverName.toLowerCase();
            serverName = serverName.split("://")[1];
            int end = serverName.indexOf(":");
            end = end != -1?end:serverName.indexOf("/");
            serverName = serverName.substring(0, end);
            String[] domains = serverName.split("\\.");
            Collections.reverse(Arrays.asList(domains));
            domainName = Arrays.stream(domains).reduce((x,y)->x+"."+y).get();
        }
        return domainName;
    }

}
